<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-d-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索栏和输入框 layout布局 gutter代表间隔  span代表长度 -->
      <el-row :gutter="30">
        <el-col :span="10">
          <!-- 搜索输入框 clearable清空按钮是否显示  @clear 清空调用的方法 -->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            :clearable="true"
            @clear="getUserList"
          >
            <!-- 搜索按钮 -->
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域  :data代表数据源 stripe隔行换色 -->
      <el-table :data="Userlist" border :stripe="true" style="width: 100%">
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <!-- prop写:data里面的key值  label代表表头 -->
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 可以获取到父组件传来的 row, column, $index 和 store（table 内部的状态管理）的数据 -->
          <template v-slot="scope">
            <!-- {{ scope.row }} 拿到的是当前行的数据对象 .mg_state就是对应状态开关的状态 -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="blue"
              inactive-color="red"
              @change="userChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="">
          <template v-slot="scope">
            <!-- 修改按钮 点击后应该去请求用户对应的数据 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 文本提示 tooltip -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top-end"
            >
              <!-- 分配角色按钮 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showEditRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 @size-change总页数改变的时候调用 @current-change当前页数改变调用
      layout 分页条的布局  total总数据条数 page-size当前页条数-->
      <el-pagination
        @size-change="handlePageSize"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框  visible.sync是否显示 before-close关闭对话框之前的逻辑-->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      :before-close="handleEditCloseCommit"
      @close="addDiologClose"
    >
      <!-- 添加用户的内容表单 -->
      <el-form
        :model="addUserForm"
        ref="addUserFormRef"
        :rules="addUserFormRules"
        label-width="100px"
      >
        <!-- prop属性在预校验的时候会用到 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="DialogVisibleCommit = true">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 取消添加用户确认对话框-->
    <el-dialog title="提示" :visible.sync="DialogVisibleCommit" width="20%">
      <span>离开对话框后信息不会保存哦</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="DialogVisibleCommit = false">不取消了</el-button>
        <el-button type="primary" @click="handleAddCloseCommit()"
          >依然取消</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改用户信息的对话框 @close关闭时候的回调 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 用户信息内容主体 -->
      <el-form
        :model="editUserForm"
        ref="editUserFormRef"
        :rules="editUserFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">修 改</el-button>
      </span>
    </el-dialog>

   <!-- 分配角色對話框 -->
 <el-dialog
  title="分配角色"
  :visible.sync="setRoleDialogVisible"
  width="50%"
  >
 <p>當前用戶:  {{userInfo.username}}</p>
 <p>當前角色:  {{userInfo.role_name}}</p>
 <p>
   請選擇角色:
   <!-- v-model和data里面的值绑定 -->
    <el-select v-model="selectRoleId" placeholder="请选择">
    <el-option
      v-for="item in roleList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  </p>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRole">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList()
  },
  data() {
    // 自定义邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        // 合法就直接callback
        return callback()
      }
      // 不合法return new error
      callback(new Error('请输入合法邮箱'))
    }
    // 自定义手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号码'))
    }

    return {
      Userlist: [],
      total: 0,
      // get网络请求需要的参数 ， 分页的时候也要用到，先抽离出来
      queryInfo: {
        // 搜索内容
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示数
        pagesize: 1
      },
      // 添加用户对话框是否显示
      addDialogVisible: false,
      // 确认取消对话框是否显示
      DialogVisibleCommit: false,
      // 用户添加
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },

      // 用户添加表单验证规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '用户名的长度在2～10个字',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          {
            min: 6,
            max: 18,
            message: '用户密码的长度在6～18个字',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      // 修改用户信息对话框显示状态
      editDialogVisible: false,
      // 修改用户的数据对象
      editUserForm: {},
      // 修改用户表单的预校验规则
      editUserFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 分配角色的對話框
      setRoleDialogVisible: false,
      // 需要分配角色的用戶的信息
      userInfo: {},
      // 所有角色信息列表
      roleList: [],
      // 編輯角色列表中當前選中的值
      selectRoleId: ''

    }
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('User信息获取失败')
      }
      this.Userlist = res.data.users
      this.total = res.data.total
    },
    // 监听switch状态改变
    // switch组件点击的时候，vmodel对应的值也会发生改变
    async userChange(userRow) {
      // put方法用于修改数据
      const { data: res } = await this.$http.put(
        `users/${userRow.id}/state/${userRow.mg_state}`
      )
      console.log('put方法的res', res)
      if (res.meta.status !== 200) {
        //  switch组件点击的时候，vmodel对应的值也会发生改变  所以要把状态改回去
        userRow.mg_state = !userRow.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 监听pagesize改变
    handlePageSize(currentPageSize) {
      this.queryInfo.pagesize = currentPageSize
      this.getUserList()
    },
    // 监听当前页数变化
    handleCurrentChange(currentPage) {
      this.queryInfo.pagenum = currentPage
      this.getUserList()
    },
    // 添加用户对话框取消之前
    beforeClose() {
      this.DialogVisibleCommit = true
    },
    // 提醒后依然取消
    handleAddCloseCommit() {
      this.DialogVisibleCommit = false
      this.addDialogVisible = false
    },
    // 添加用户的方法
    addUser() {
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) return false
        try {
          const { data: res } = await this.$http.post('users', this.addUserForm)
          console.log(res)
          if (res.meta.status !== 201) {
            this.$message.error('添加用户失败！' + res.meta.status)
          } else this.$message.success('添加用户成功！')
          // 隐藏添加用户对话框
          this.addDialogVisible = false
          // 重新请求一次新数据
          this.getUserList()
        } catch (error) {
          this.$message.error('接口错误')
        }
      })
    },

    // 关闭添加用户对话框时候的回调函数
    addDiologClose() {
      this.$refs.addUserFormRef.resetFields()
    },

    // 关闭编辑用户对话框时候的回调函数
    editDialogClosed() {
      this.$refs.editUserFormRef.resetFields()
    },

    // 编辑按钮点击后显示对话框 并且读数据
    async showEditDialog(userId) {
      const { data: res } = await this.$http.get('users/' + userId)
      this.editUserForm = res.data
      console.log('编辑按钮读到的数据是', res.data)
      // this.editUserForm = { ...this.editUserForm }
      this.editDialogVisible = true
    },

    // 修改用户信息
    editUser() {
      this.$refs.editUserFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editUserForm.id,
          {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('更新用户信息失败！')
        }
        // 隐藏添加用户对话框
        this.editDialogVisible = false
        this.$message.success('更新用户信息成功！')
        this.getUserList()
      })
    },

    // 编辑用户界面依然取消
    handleEditCloseCommit() {
      this.editDialogVisible = false
      this.DialogVisibleCommit = false
    },

    // 删除用户
    removeUserById(userId) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('users/' + userId)
          if (res.meta.status !== 200) return
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 删除成功后刷新列表
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 顯示分配角色對話框
    showEditRoleDialog(user) {
      this.userInfo = user
      this.setRoleDialogVisible = true
      // 獲取所有角色列表
      this.$http.get('roles').then(res => {
        this.roleList = res.data.data
      }).catch(err => this.$message.error('請求角色列表失敗', err))
    },

    // 分配角色
    setRole() {
      if (!this.selectRoleId) {
        return this.$message.error('請輸入要分配的角色')
      }

      this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectRoleId }).then(res => {
        console.log(res)
        if (res.data.meta.status !== 200) return this.$message.error('分配角色失敗')
        this.$message.success('分配角色成功')
        this.setRoleDialogVisible = false
        this.getUserList()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}
.el-card {
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.15) !important;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>
